<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>智能单车治理系统</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
            background: white;
            border-radius: 15px;
            box-shadow: 0 20px 40px rgba(0,0,0,0.1);
            overflow: hidden;
        }

        .header {
            background: linear-gradient(135deg, #2c3e50, #34495e);
            color: white;
            padding: 30px;
            text-align: center;
        }

        .header h1 {
            font-size: 2.5em;
            margin-bottom: 10px;
        }

        .header .subtitle {
            font-size: 1.2em;
            opacity: 0.9;
        }

        .main-content {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 30px;
            padding: 30px;
        }

        @media (max-width: 768px) {
            .main-content {
                grid-template-columns: 1fr;
            }
        }

        .chat-section, .info-section {
            background: #f8f9fa;
            border-radius: 10px;
            padding: 25px;
        }

        .chat-box {
            height: 400px;
            border: 1px solid #e9ecef;
            border-radius: 8px;
            padding: 15px;
            overflow-y: auto;
            background: white;
            margin-bottom: 20px;
        }

        .message {
            margin-bottom: 15px;
            padding: 12px;
            border-radius: 8px;
            line-height: 1.5;
        }

        .user-message {
            background: #e3f2fd;
            border-left: 4px solid #2196f3;
        }

        .bot-message {
            background: #f3e5f5;
            border-left: 4px solid #9c27b0;
        }

        .input-group {
            display: flex;
            gap: 10px;
        }

        input[type="text"] {
            flex: 1;
            padding: 12px 15px;
            border: 1px solid #ddd;
            border-radius: 8px;
            font-size: 16px;
        }

        button {
            padding: 12px 25px;
            background: linear-gradient(135deg, #667eea, #764ba2);
            color: white;
            border: none;
            border-radius: 8px;
            cursor: pointer;
            font-size: 16px;
            transition: all 0.3s ease;
        }

        button:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(0,0,0,0.2);
        }

        button:disabled {
            background: #ccc;
            cursor: not-allowed;
            transform: none;
        }

        .source-doc {
            background: white;
            border: 1px solid #e9ecef;
            border-radius: 6px;
            padding: 12px;
            margin-top: 10px;
            font-size: 0.9em;
        }

        .source-doc .source {
            font-weight: bold;
            color: #667eea;
        }

        .stats {
            display: flex;
            justify-content: space-between;
            margin-top: 15px;
            font-size: 0.9em;
            color: #666;
        }

        .loading {
            text-align: center;
            color: #667eea;
            font-style: italic;
        }

        .error {
            color: #e74c3c;
            background: #ffeaea;
            padding: 10px;
            border-radius: 5px;
            margin: 10px 0;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>🚲 智能单车治理系统</h1>
            <div class="subtitle">基于AI的智能问答与文档分析平台</div>
        </div>

        <div class="main-content">
            <div class="chat-section">
                <h2>💬 智能问答</h2>
                <div class="chat-box" id="chatBox">
                    <div class="message bot-message">
                        您好！我是智能单车治理助手，可以回答关于共享单车管理、城市交通治理等相关问题。请问有什么可以帮您的？
                    </div>
                </div>

                <div class="input-group">
                    <input type="text" id="questionInput" placeholder="请输入您关于单车治理的问题..." onkeypress="handleKeyPress(event)">
                    <button onclick="askQuestion()" id="askButton">发送</button>
                </div>

                <div class="stats">
                    <div>模型: llama3:8b</div>
                    <div id="responseTime">响应时间: -</div>
                </div>
            </div>

            <div class="info-section">
                <h2>📊 系统信息</h2>
                <div id="systemInfo">
                    <p>正在检查系统状态...</p>
                </div>

                <h3 style="margin-top: 20px;">💡 示例问题</h3>
                <ul style="margin-left: 20px; margin-top: 10px; line-height: 1.6;">
                    <li>单车乱停乱放造成的城市交通问题有哪些？</li>
                    <li>如何有效管理共享单车的停放？</li>
                    <li>智能单车治理系统的主要功能是什么？</li>
                    <li>共享单车对城市环境的影响有哪些？</li>
                </ul>

                <div style="margin-top: 20px; padding: 15px; background: #e8f5e8; border-radius: 8px;">
                    <strong>🔧 技术架构</strong>
                    <p style="margin-top: 8px; font-size: 0.9em;">
                        FastAPI + Ollama + LangChain + FAISS<br>
                        支持中文文档检索与智能问答
                    </p>
                </div>
            </div>
        </div>
    </div>

    <script>
        const API_BASE = 'http://localhost:8000';

        // 检查系统状态
        async function checkSystemStatus() {
            try {
                const response = await fetch(`${API_BASE}/health`);
                const data = await response.json();

                const systemInfo = document.getElementById('systemInfo');
                if (data.status === 'healthy' && data.rag_initialized) {
                    systemInfo.innerHTML = `
                        <p style="color: #27ae60;">✅ 系统运行正常</p>
                        <p>模型: ${data.model || 'llama3:8b'}</p>
                        <p>状态: 已就绪，可以回答问题</p>
                    `;
                } else {
                    systemInfo.innerHTML = `
                        <p style="color: #e74c3c;">⚠️ 系统未完全就绪</p>
                        <p>状态: ${data.rag_initialized ? 'RAG已初始化' : 'RAG未初始化'}</p>
                    `;
                }
            } catch (error) {
                document.getElementById('systemInfo').innerHTML = `
                    <p style="color: #e74c3c;">❌ 无法连接到后端服务</p>
                    <p>请确保FastAPI服务正在运行在 localhost:8000</p>
                `;
            }
        }

        // 提问函数
        async function askQuestion() {
            const input = document.getElementById('questionInput');
            const button = document.getElementById('askButton');
            const question = input.value.trim();

            if (!question) return;

            // 禁用输入和按钮
            input.disabled = true;
            button.disabled = true;
            button.textContent = '思考中...';

            // 添加用户消息到聊天框
            addMessage(question, 'user');
            input.value = '';

            // 显示加载状态
            const loadingId = addMessage('正在思考中，请稍候...', 'bot', true);

            // 添加 chat_id
            let chatId = localStorage.getItem("chat_id");
            if (!chatId) {
                chatId = crypto.randomUUID();
                localStorage.setItem("chat_id", chatId);
            }

            try {
                const response = await fetch(`${API_BASE}/ask`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({ question: question, chat_id: chatId }),
                });

                const data = await response.json();

                // 移除加载消息
                removeMessage(loadingId);

                if (response.ok) {
                    // 添加AI回答
                    let answerHtml = data.answer;

                    // 添加源文档信息
                    if (data.source_documents && data.source_documents.length > 0) {
                        answerHtml += `<div style="margin-top: 15px;"><strong>📚 参考来源:</strong>`;
                        data.source_documents.forEach(doc => {
                            answerHtml += `
                                <div class="source-doc">
                                    <div class="source">来源: ${doc.source} (片段: ${doc.chunk_index})</div>
                                    <div>${doc.content_preview}</div>
                                </div>
                            `;
                        });
                        answerHtml += `</div>`;
                    }

                    addMessage(answerHtml, 'bot');

                    // 更新响应时间
                    document.getElementById('responseTime').textContent =
                        `响应时间: ${data.processing_time}秒`;
                } else {
                    addMessage(`错误: ${data.detail}`, 'bot');
                }
            } catch (error) {
                removeMessage(loadingId);
                addMessage(`网络错误: 无法连接到服务器。请确保后端服务正在运行。`, 'bot');
            } finally {
                // 重新启用输入和按钮
                input.disabled = false;
                button.disabled = false;
                button.textContent = '发送';
                input.focus();
            }
        }

        // 添加消息到聊天框
        function addMessage(content, type, isTemp = false) {
            const chatBox = document.getElementById('chatBox');
            const messageId = isTemp ? 'temp-' + Date.now() : null;

            const messageDiv = document.createElement('div');
            messageDiv.className = `message ${type}-message`;
            messageDiv.innerHTML = content;

            if (isTemp) {
                messageDiv.id = messageId;
                messageDiv.classList.add('loading');
            }

            chatBox.appendChild(messageDiv);
            chatBox.scrollTop = chatBox.scrollHeight;

            return messageId;
        }

        // 移除临时消息
        function removeMessage(messageId) {
            const message = document.getElementById(messageId);
            if (message) {
                message.remove();
            }
        }

        // 处理回车键
        function handleKeyPress(event) {
            if (event.key === 'Enter') {
                askQuestion();
            }
        }

        // 页面加载时检查系统状态
        window.onload = function() {
            checkSystemStatus();
            document.getElementById('questionInput').focus();
        };
    </script>
</body>
</html>